package xyz.xtt.asset.mq;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import xyz.xtt.asset.request.MystryBoxMessage;
import xyz.xtt.asset.service.IMystryBoxService;

import java.util.Objects;

/**
 * @author huqibo
 * @date 2024/12/26
 */
@RefreshScope
@Slf4j
@Component
@RocketMQMessageListener(topic = "${rocketmq.consumer.everydaymsg:QUDAO_SEND_ORDER}", selectorExpression = "${rocketmq.consumer.mystryboxtag:QUDAO_SEND_ORDER_SKU0003_TAG}", consumerGroup = "${rocketmq.consumer.group.mystrybox}")
public class MystryBoxMessageConsumer implements RocketMQListener<String> {
	@Autowired
	private IMystryBoxService iMystryBoxService;

	@Value("${rocketmq.consumer.mystryboxmsg:QUDAO_SEND_ORDER}")
	private String topic;
	@Value("${activity.send.mystryBox:true}")
	private Boolean sendMystryBoxSwitch;

	@Override
	public void onMessage(String message) {
		log.info("onMessage mystryBoxMessage topic:{} Received message: {}", topic, message);
		if (StringUtils.isEmpty(message)) {
			return;
		} else if(!JSONUtil.isTypeJSON(message)){
			log.error("onMessage mystryBoxMessage topic:{} Received message: {} is not json", topic, message);
			return;
		}
		if (Objects.equals(Boolean.FALSE, sendMystryBoxSwitch)) {
			log.info("mystryBoxMessage topic:{} sendMystryBoxSwitch:{} is close", topic, sendMystryBoxSwitch);
			return;
		}
		MystryBoxMessage mystryBox = JSONUtil.toBean(message, MystryBoxMessage.class);
		if (Objects.isNull(mystryBox)) {
			log.info("mystryBoxMessage topic:{} JSONUtil.toBean is null", topic);
			return;
		}
		try {
			// 发元素礼包
			Boolean sendEveryDayGriftbox = iMystryBoxService.sendMystryBox(mystryBox);
			log.info("mystryBoxMessage: {}:msg:{} ", sendEveryDayGriftbox, JSONUtil.toJsonStr(mystryBox));
		} catch (Exception e) {
			log.info("mystryBoxMessage ex:{}", e.getMessage(), e);
			throw new RuntimeException("onMessage mystryBoxMessage");
		}
	}

}
